<?php

class AppController extends Controller {

    var $name = 'App';
    var $helpers = array('Html', 'javascript', 'Ajax', 'Session', 'Js', 'Access', 'PhpThumb', 'Time');
    var $components = array('RequestHandler', 'Auth', 'Session', 'Acl', 'Access', 'Cookie');
    
    function beforeFilter() {
        parent::beforeFilter();
        $this->Cookie->key = 'gU67&5#^&(78aAmKIk5)';
        if (!isset($this->params['admin'])) {
            $this->Auth->loginAction = array('admin' => false, 'controller' => 'Homes', 'action' => 'index');

            if (!$this->Auth->User('id') && (!isset($this->data))) {
                //$this->check_cookie();
            } else {
                $this->upgrade_account();
                $this->_set_permissions();
            }
        }
    }

    function beforeRender() {

        if (!isset($_SESSION['Auth']['admin'])) {
            $_SESSION['Auth']['admin']['User'] = null;
        } else if (!isset($_SESSION['Auth']['user'])) {
            $_SESSION['Auth']['user']['User'] = null;
        }
        if (isset($_SESSION['Auth']['User']) || isset($_SESSION['Auth']['admin']['User']) || isset($_SESSION['Auth']['user']['User'])) {
            if (isset($this->params['admin'])) {

                $_SESSION['Auth']['User'] = $_SESSION['Auth']['admin']['User'];
            } else {
                $_SESSION['Auth']['User'] = $_SESSION['Auth']['user']['User'];
            }
        }

        App::import("Component", "Captcha"); //including captcha class
        $this->Captcha = new CaptchaComponent(); //creating an object instance
        $this->Captcha->controller = & $this; //assign this conroller(CaptchaController) object to its captcha object's controller property.
        //$captcha_src = $this->Captcha->create();
        $this->set('captcha_src', $captcha_src = $this->Captcha->create());

        if (preg_match("/^admin/", $this->params['url']['url']) && !isset($this->params['admin']) && !empty($this->Auth->_loggedIn)) {
            if (!$this->Access->check('Subject', 'read')) {
                $this->Session->setFlash('You dont have permissions to View this content ');

                //$this->redirect($this->Auth->logout());
                $this->redirect('Dashboard/index');
            }
        }

        if (isset($this->params['admin']) && $this->params['url']['url'] != "admin/users/login") {
            $this->layout = 'admin_default';

            $_SESSION['points'] = $this->get_points($_SESSION['Auth']['admin']['User']['id']);
        } else {
            if ($this->Auth->User('id')) {
                $this->upgrade_account();
            }
        }

        if (isset($_SESSION['Auth']['user'])) {
            $_SESSION['points'] = $this->get_points($_SESSION['Auth']['user']['User']['id']);            
        }
        if (!isset($this->params['admin'])) {
            $this->Auth->loginAction = array('admin' => false, 'controller' => 'Homes', 'action' => 'index');
        }
    }

    function get_points($id) {
        if ($id) {
            $data = mysql_query("SELECT SUM(credit) as points from `user_credits` where `user_id`='$id'");
            $points = mysql_fetch_array($data);
            if ($data) {
                $points = $points['points'];
            } else {
                $points = 0;
            }
        } else {
            $points = 0;
        }
        return $points;
    }

    function upgrade_account() {
        //echo echo $this->Session->flash();debug($_SESSION['flash']);//die();

        $this->loadModel('User');
        $this->loadModel('Memberplan');
        $this->User->unbindModel(array('hasMany' => array('UserCredit', 'Subject', 'SubjectRate')));
        $data = $this->User->find('first', array('conditions' => array('User.id' => $this->Auth->User('id')), 'fields' => array('UserProfile.account_type', 'UserProfile.paid_account_created', 'UserProfile.duration', 'UserProfile.free_account_type', 'UserProfile.free_account_created')));
        if (!$data['UserProfile']['account_type']) {
            $points = $this->get_points($this->Auth->User('id'));
            $upgrade_limit = $this->Memberplan->find('all', array('fields' => array('Memberplan.title', 'Memberplan.points', 'Memberplan.duration'), 'order' => 'Memberplan.points'));
            $free_plan = null;
            $free_plan_duration = null;
            foreach ($upgrade_limit as $plan) {
                if ($points % $plan['Memberplan']['points'] == '0') {
                    $free_plan = $plan['Memberplan']['title'];
                    $free_plan_duration = $plan['Memberplan']['duration'];
                }
            }
            if ($free_plan && $_SESSION['free_plan'] == 'free') {                                  // User has got free account set it in session and update users profile;
                $_SESSION['free_plan'] = $free_plan;
                $update_profile = mysql_query("UPDATE user_profiles set `free_account_type`='$free_plan', `free_account_created`=NOW() WHERE `user_id`='" . $this->Auth->User('id') . "'") or die(mysql_error());
            } else {

                $_SESSION['free_plan'] = 'free';
            }
            //debug($upgrade_limit);
        }
        //debug($data);die();
    }

    function check_cookie() {
        if ($this->Cookie->read('User')) {
            $this->data = $this->Cookie->read('User');
//            debug($this->data);
            if ($this->Auth->login($this->data)) {
                $_SESSION['Auth']['user']['User'] = $_SESSION['Auth']['User'];
                $this->_set_permissions();
                $this->Session->setFlash('Welcome User');
                $this->redirect(array('controller' => 'Homes', 'action' => 'index'));
            }
            //$this->data['User']['username']=;
            //$this->data['User']['password']=;
        }
    }

    function _set_permissions() {
        $get_age = $this->User->UserProfile->query("SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(),`dob`)), '%Y')+0 AS age from user_profiles where user_id='" . $this->Auth->User('id') . "'");

        if ($get_age) {
            if ($get_age['0']['0']['age'] > 17) {
                $_SESSION['above_17'] = true;
            } else {
                $_SESSION['above_17'] = false;
            }
        } else {
            $_SESSION['above_17'] = false;
        }
    }

}

?>